

import numpy as np
import pandas as pd
import yaml
from pandas import DataFrame
from pymysql.connections import Connection
from yaml import SafeLoader

from datareport.api import ImageUtil
from datareport.api.DataSource import DataSource
from datareport.api.annotation.Font import Font
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style
from datareport.impl import StaticDF


@style()
class JiHua_ShiJianFenBu_15(BaseParagraph):
    """
    时间分布
    """

    def __init__(self):
        super().__init__()
        self.text = '''（1）从时间分布来看：{}月计划场次最高，为{}场次，平均{}场次/支部；{}月计划场次最低，为{}场次，平均{}场次/支部'''
        self.Fonts: [Font]=[]
        self.sort = 6
        self.section=1

    def plot(self, result:DataFrame, plt):
        result['month']=result['month'].astype(int)
        x_arr=np.arange(1,13)
        for x in x_arr:
            if len(result[result['month']==x])==0:
                result=result.append({'month':x,'num':0},ignore_index=True)
        result.sort_values('month',inplace=True)
        result.rename(columns={"month":"月份","num":"数量"},inplace=True)
        result['月份']=result['月份'].astype(str)
        result['月份']=result['月份'].apply(lambda x:x+'月')
        self.image=ImageUtil.plot(result)


    def getData(self,result):
        pass

    def start(self,conn:Connection,year,plt):
        # cursor=conn.cursor()
        sql = '''
                select month ,partyBranchCode,left(partyBranchName,2)partyBranchName,
                left(partyOrgName,2) partyOrgName
                from t_meetingPlan
                where year(startTime)='{year}' and isPlan=1
                '''.format(year=year)
        df = pd.read_sql(sql, con=conn)
        df['num']=1
        count_month_df = df.groupby('month')['num'].count()
        # 场次最高最低
        max_df = df[df['month'] == count_month_df.idxmax()]
        loss=list(set(np.arange(1,13))-set(df['month'].drop_duplicates().tolist()))
        max_avg_ = round(len(max_df) / len(max_df['partyBranchCode'].drop_duplicates()))

        if len(loss)==0:
            min_num=count_month_df.min()
            min_df = df[df['month'].isin(count_month_df[count_month_df==min_num].index.tolist())]
            min_month='、'.join(min_df['month'].values.tolist())
            len_min_df=len(min_df)
            min_avg_ = round(len(min_df) / len(min_df['partyBranchCode'].drop_duplicates()))

        else:
            min_month='、'.join(str(i) for i in loss)
            len_min_df=0
            min_avg_=0

        self.text=self.text.format(max_df['month'].values[0], len(max_df),max_avg_ ,
                         min_month, len_min_df, min_avg_)
        self.fonts.append(Font(text=self.text))
        self.plot(count_month_df.reset_index(drop=False), plt)

        StaticDF.data = df

if __name__ == '__main__':
    with open('D:\work\sanhuiyike\datareport\config.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)
    con = DataSource(data['datasource']).conn
    JiHua_ShiJianFenBu_15().start(con, 2023, '')